# -*- coding: utf-8 -*-

"""邮件发送"""

import os
import re
import time
import smtplib
import email
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def send(mail_, host_):
    # 连接邮件服务器
    smtp = smtplib.SMTP(timeout=90)
    # smtp.set_debuglevel(1)
    try:
        smtp.connect(host_['host'])
        smtp.login(host_['user'], host_['pass'])
    except Exception as ex:
        return

    # 发送邮件
    msg = _buildMessage(
        mail_['from'],
        mail_['to'],
        mail_['subject'],
        mail_['body'])
    try:
        smtp.sendmail(mail_['from'], mail_['to'], msg.as_string())
    except Exception as ex:
        pass

    # 关闭连接
    smtp.quit()


def _buildMessage(from_, to_, subject_, body_):
    """设定邮件内容"""

    # From 地址编码(支持 中文名<abc@email.com> 格式)
    pos = from_.find('<')
    if pos > -1:
        fh = Header(from_[0:pos], 'utf-8')
        fh.append(from_[pos:], 'ascii')
    else:
        fh = Header(from_, 'ascii')

    # 邮件内容
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = Header(subject_, 'utf-8')
    msgRoot['From'] = fh
    msgRoot['To'] = to_
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to
    # display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    # 设定纯文本信息
    # msgText = MIMEText(plainText, 'plain', 'utf-8')
    # msgAlternative.attach(msgText)

    # 设定HTML信息
    msgText = MIMEText(body_, 'html', 'utf-8')
    msgAlternative.attach(msgText)

    return msgRoot
